package com.dt.platform.oa.controller;

import java.util.*;
import com.dt.platform.proxy.oa.ProjectTaskServiceProxy;
import com.github.foxnic.sql.expr.OrderBy;
import org.github.foxnic.web.domain.hrm.Person;
import org.github.foxnic.web.framework.web.SuperController;
import org.simpleframework.xml.Order;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import com.github.foxnic.commons.collection.CollectorUtil;
import com.github.foxnic.dao.entity.ReferCause;
import com.github.foxnic.api.swagger.InDoc;
import org.github.foxnic.web.framework.sentinel.SentinelExceptionUtil;
import com.github.foxnic.api.swagger.ApiParamSupport;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dt.platform.proxy.oa.ProjectPhaseServiceProxy;
import com.dt.platform.domain.oa.meta.ProjectPhaseVOMeta;
import com.dt.platform.domain.oa.ProjectPhase;
import com.dt.platform.domain.oa.ProjectPhaseVO;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.dao.data.SaveMode;
import com.github.foxnic.dao.excel.ExcelWriter;
import com.github.foxnic.springboot.web.DownloadUtil;
import com.github.foxnic.dao.data.PagedList;
import java.util.Date;
import java.sql.Timestamp;
import com.github.foxnic.api.error.ErrorDesc;
import com.github.foxnic.commons.io.StreamUtil;
import java.util.Map;
import com.github.foxnic.dao.excel.ValidateResult;
import java.io.InputStream;
import com.dt.platform.domain.oa.meta.ProjectPhaseMeta;
import org.github.foxnic.web.domain.hrm.Employee;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiImplicitParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dt.platform.oa.service.IProjectPhaseService;
import com.github.foxnic.api.validate.annotations.NotNull;

/**
 * <p>
 * 项目阶段接口控制器
 * </p>
 * @author 金杰 , maillank@qq.com
 * @since 2025-06-19 08:34:10
 */
@InDoc
@Api(tags = "项目阶段")
@RestController("OaProjectPhaseController")
public class ProjectPhaseController extends SuperController {

    @Autowired
    private IProjectPhaseService projectPhaseService;

    /**
     * 添加项目阶段
     */
    @ApiOperation(value = "添加项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.CT, value = "阶段说明", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.EDATE, value = "结束日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.LEADER_ID, value = "阶段负责人", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.NAME, value = "阶段名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.PROJECT_ID, value = "项目名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.RK, value = "阶段", required = false, dataTypeClass = Integer.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.SDATE, value = "开始日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL, value = "阶段模版", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL_STATUS, value = "启用模版", required = false, dataTypeClass = String.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true, ignorePrimaryKey = true)
    @ApiOperationSupport(order = 1, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.INSERT, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.INSERT)
    public Result insert(ProjectPhaseVO projectPhaseVO) {
        Result result = projectPhaseService.insert(projectPhaseVO, false);
        return result;
    }

    /**
     * 删除项目阶段
     */
    @ApiOperation(value = "删除项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class)
	})
    @ApiOperationSupport(order = 2, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.DELETE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.DELETE)
    public Result deleteById(String id) {
        this.validator().asserts(id).require("缺少id值");
        if (this.validator().failure()) {
            return this.validator().getFirstResult();
        }
        // 引用校验
        ReferCause cause = projectPhaseService.hasRefers(id);
        // 判断是否可以删除
        this.validator().asserts(cause.hasRefer()).requireEqual("不允许删除当前记录：" + cause.message(), false);
        if (this.validator().failure()) {
            return this.validator().getFirstResult().messageLevel4Confirm();
        }
        Result result = projectPhaseService.deleteByIdLogical(id);
        return result;
    }

    /**
     * 批量删除项目阶段 <br>
     * 联合主键时，请自行调整实现
     */
    @ApiOperation(value = "批量删除项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.IDS, value = "主键清单", required = true, dataTypeClass = List.class, example = "[1,3,4]")
	})
    @ApiOperationSupport(order = 3, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.DELETE_BY_IDS, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.DELETE_BY_IDS)
    public Result deleteByIds(List<String> ids) {
        // 参数校验
        this.validator().asserts(ids).require("缺少ids参数");
        if (this.validator().failure()) {
            return this.validator().getFirstResult();
        }
        // 查询引用
        Map<String, ReferCause> causeMap = projectPhaseService.hasRefers(ids);
        // 收集可以删除的ID值
        List<String> canDeleteIds = new ArrayList<>();
        for (Map.Entry<String, ReferCause> e : causeMap.entrySet()) {
            if (!e.getValue().hasRefer()) {
                canDeleteIds.add(e.getKey());
            }
        }
        // 执行删除
        if (canDeleteIds.isEmpty()) {
            // 如果没有一行可以被删除
            return ErrorDesc.failure().message("无法删除您选中的数据行：").data(0).addErrors(CollectorUtil.collectArray(CollectorUtil.filter(causeMap.values(), (e) -> {
                return e.hasRefer();
            }), ReferCause::message, String.class)).messageLevel4Confirm();
        } else if (canDeleteIds.size() == ids.size()) {
            // 如果全部可以删除
            Result result = projectPhaseService.deleteByIdsLogical(canDeleteIds);
            return result;
        } else if (canDeleteIds.size() > 0 && canDeleteIds.size() < ids.size()) {
            // 如果部分行可以删除
            Result result = projectPhaseService.deleteByIdsLogical(canDeleteIds);
            if (result.failure()) {
                return result;
            } else {
                return ErrorDesc.success().message("已删除 " + canDeleteIds.size() + " 行，但另有 " + (ids.size() - canDeleteIds.size()) + " 行数据无法删除").data(canDeleteIds.size()).addErrors(CollectorUtil.collectArray(CollectorUtil.filter(causeMap.values(), (e) -> {
                    return e.hasRefer();
                }), ReferCause::message, String.class)).messageLevel4Confirm();
            }
        } else {
            // 理论上，这个分支不存在
            return ErrorDesc.success().message("数据删除未处理");
        }
    }

    /**
     * 更新项目阶段
     */
    @ApiOperation(value = "更新项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.CT, value = "阶段说明", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.EDATE, value = "结束日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.LEADER_ID, value = "阶段负责人", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.NAME, value = "阶段名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.PROJECT_ID, value = "项目名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.RK, value = "阶段", required = false, dataTypeClass = Integer.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.SDATE, value = "开始日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL, value = "阶段模版", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL_STATUS, value = "启用模版", required = false, dataTypeClass = String.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true)
    @ApiOperationSupport(order = 4, author = "金杰 , maillank@qq.com", ignoreParameters = { ProjectPhaseVOMeta.PAGE_INDEX, ProjectPhaseVOMeta.PAGE_SIZE, ProjectPhaseVOMeta.SEARCH_FIELD, ProjectPhaseVOMeta.FUZZY_FIELD, ProjectPhaseVOMeta.SEARCH_VALUE, ProjectPhaseVOMeta.DIRTY_FIELDS, ProjectPhaseVOMeta.SORT_FIELD, ProjectPhaseVOMeta.SORT_TYPE, ProjectPhaseVOMeta.DATA_ORIGIN, ProjectPhaseVOMeta.QUERY_LOGIC, ProjectPhaseVOMeta.REQUEST_ACTION, ProjectPhaseVOMeta.IDS })
    @SentinelResource(value = ProjectPhaseServiceProxy.UPDATE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.UPDATE)
    public Result update(ProjectPhaseVO projectPhaseVO) {
        Result result = projectPhaseService.update(projectPhaseVO, SaveMode.DIRTY_OR_NOT_NULL_FIELDS, false);
        return result;
    }

    /**
     * 保存项目阶段
     */
    @ApiOperation(value = "保存项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.CT, value = "阶段说明", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.EDATE, value = "结束日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.LEADER_ID, value = "阶段负责人", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.NAME, value = "阶段名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.PROJECT_ID, value = "项目名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.RK, value = "阶段", required = false, dataTypeClass = Integer.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.SDATE, value = "开始日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL, value = "阶段模版", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL_STATUS, value = "启用模版", required = false, dataTypeClass = String.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true)
    @ApiOperationSupport(order = 5, ignoreParameters = { ProjectPhaseVOMeta.PAGE_INDEX, ProjectPhaseVOMeta.PAGE_SIZE, ProjectPhaseVOMeta.SEARCH_FIELD, ProjectPhaseVOMeta.FUZZY_FIELD, ProjectPhaseVOMeta.SEARCH_VALUE, ProjectPhaseVOMeta.DIRTY_FIELDS, ProjectPhaseVOMeta.SORT_FIELD, ProjectPhaseVOMeta.SORT_TYPE, ProjectPhaseVOMeta.DATA_ORIGIN, ProjectPhaseVOMeta.QUERY_LOGIC, ProjectPhaseVOMeta.REQUEST_ACTION, ProjectPhaseVOMeta.IDS })
    @SentinelResource(value = ProjectPhaseServiceProxy.SAVE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.SAVE)
    public Result save(ProjectPhaseVO projectPhaseVO) {
        Result result = projectPhaseService.save(projectPhaseVO, SaveMode.DIRTY_OR_NOT_NULL_FIELDS, false);
        return result;
    }

    /**
     * 获取项目阶段
     */
    @ApiOperation(value = "获取项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class, example = "1")
	})
    @ApiOperationSupport(order = 6, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.GET_BY_ID, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.GET_BY_ID)
    public Result<ProjectPhase> getById(String id) {
        Result<ProjectPhase> result = new Result<>();
        ProjectPhase projectPhase = projectPhaseService.getById(id);
        // join 关联的对象
        projectPhaseService.dao().fill(projectPhase).with("leader").with(ProjectPhaseMeta.PART_USER_LIST).execute();
        projectPhaseService.dao().join(projectPhase.getLeader(), Person.class);
        List<Employee> userList = projectPhase.getPartUserList();
        if (userList != null && userList.size() > 0) {
            projectPhaseService.dao().join(userList, Person.class);
        }
        result.success(true).data(projectPhase);
        return result;
    }

    /**
     * 批量获取项目阶段 <br>
     * 联合主键时，请自行调整实现
     */
    @ApiOperation(value = "批量获取项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.IDS, value = "主键清单", required = true, dataTypeClass = List.class, example = "[1,3,4]")
	})
    @ApiOperationSupport(order = 3, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.GET_BY_IDS, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.GET_BY_IDS)
    public Result<List<ProjectPhase>> getByIds(List<String> ids) {
        Result<List<ProjectPhase>> result = new Result<>();
        List<ProjectPhase> list = projectPhaseService.queryListByIds(ids);
        result.success(true).data(list);
        return result;
    }

    @ApiOperation(value = "动作")
    @ApiOperationSupport(order = 2, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.ACTION, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.ACTION)
    public Result action(String id, String action, String ct) {
        Result result = projectPhaseService.action(id, action, ct);
        return result;
    }

    /**
     * 查询项目阶段
     */
    @ApiOperation(value = "查询项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.CT, value = "阶段说明", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.EDATE, value = "结束日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.LEADER_ID, value = "阶段负责人", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.NAME, value = "阶段名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.PROJECT_ID, value = "项目名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.RK, value = "阶段", required = false, dataTypeClass = Integer.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.SDATE, value = "开始日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL, value = "阶段模版", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL_STATUS, value = "启用模版", required = false, dataTypeClass = String.class)
	})
    @ApiOperationSupport(order = 5, author = "金杰 , maillank@qq.com", ignoreParameters = { ProjectPhaseVOMeta.PAGE_INDEX, ProjectPhaseVOMeta.PAGE_SIZE })
    @SentinelResource(value = ProjectPhaseServiceProxy.QUERY_LIST, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.QUERY_LIST)
    public Result<List<ProjectPhase>> queryList(ProjectPhaseVO sample) {
        Result<List<ProjectPhase>> result = new Result<>();
        List<ProjectPhase> list = projectPhaseService.queryList(sample);
        result.success(true).data(list);
        return result;
    }

    /**
     * 分页查询项目阶段
     */
    @ApiOperation(value = "分页查询项目阶段")
    @ApiImplicitParams({
		@ApiImplicitParam(name = ProjectPhaseVOMeta.CT, value = "阶段说明", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.EDATE, value = "结束日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.LEADER_ID, value = "阶段负责人", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.NAME, value = "阶段名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.PROJECT_ID, value = "项目名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.RK, value = "阶段", required = false, dataTypeClass = Integer.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.SDATE, value = "开始日期", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL, value = "阶段模版", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = ProjectPhaseVOMeta.TPL_STATUS, value = "启用模版", required = false, dataTypeClass = String.class)
	})
    @ApiOperationSupport(order = 8, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = ProjectPhaseServiceProxy.QUERY_PAGED_LIST, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(ProjectPhaseServiceProxy.QUERY_PAGED_LIST)
    public Result<PagedList<ProjectPhase>> queryPagedList(ProjectPhaseVO sample) {
        Result<PagedList<ProjectPhase>> result = new Result<>();
        OrderBy order = new OrderBy();
        order.asc("rk");
        PagedList<ProjectPhase> list = projectPhaseService.queryPagedList(sample, order, sample.getPageSize(), sample.getPageIndex());
        // join 关联的对象
        projectPhaseService.dao().fill(list).with("leader").with(ProjectPhaseMeta.PART_USER_LIST).execute();
        List<Employee> leaders = CollectorUtil.collectList(list, ProjectPhase::getLeader);
        projectPhaseService.dao().join(leaders, Person.class);
        List<List<Employee>> userList = CollectorUtil.collectList(list, ProjectPhase::getPartUserList);
        List<Employee> member = userList.stream().collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);
        projectPhaseService.dao().join(member, Person.class);
        result.success(true).data(list);
        return result;
    }
}
